<template>
	<div class="page-info">
		<div class="search">
			<div class="search-box">
				<a-form
					:model="searchInfo"
					:label-col="labelCol"
					:wrapper-col="wrapperCol"
				>
					<a-row :gutter="24">
						<a-col :span="8">
							<a-form-item
								:name="labelMap['datingType'].name"
								:label="labelMap['datingType'].label"
							>
								<a-select
									style="width: 90%; margin-left: 8px"
									ref="select"
									v-model:value="searchInfo.datingType"
									:placeholder="'请输入' + labelMap['datingType'].label"
									:field-names="{ label: 'typeName', value: 'typeCode' }"
									:options="datingTypeList"
									:allowClear="true"
								>
								</a-select>
							</a-form-item>
						</a-col>
						<a-col :span="8">
							<a-form-item
								:name="labelMap['startTimeFrom'].name"
								:label="labelMap['startTimeFrom'].label"
							>
								<a-date-picker
									v-model:value="searchInfo.startTimeFrom"
									:placeholder="'请填写' + labelMap['startTimeFrom'].label"
									allow-clear
								/>
							</a-form-item>
						</a-col>
						<a-col :span="8">
							<a-form-item
								:name="labelMap['startTimeTo'].name"
								:label="labelMap['startTimeTo'].label"
							>
								<a-date-picker
									v-model:value="searchInfo.startTimeTo"
									:placeholder="'请填写' + labelMap['startTimeTo'].label"
									allow-clear
								/>
							</a-form-item>
						</a-col>
					</a-row>
					<a-row :gutter="24">
						<a-col :span="8">
							<a-form-item
								:name="labelMap['content'].name"
								:label="labelMap['content'].label"
							>
								<a-input
									style="width: 90%; margin-left: 8px"
									v-model:value="searchInfo.content"
									:placeholder="'请填写' + labelMap['content'].label"
									allow-clear
								/>
							</a-form-item>
						</a-col>
						<a-col style="text-align: right; margin-bottom: 20px">
							<a-space>
								<a-button type="primary" @click="query"> 查找</a-button>
								<a-button type="primary" @click="cancelQuery">清空</a-button>
							</a-space>
						</a-col>
					</a-row>
				</a-form>
			</div>
		</div>
		<div class="button" style="margin: 10px">
			<a-space>
				<a-button type="primary" @click="editDatingInfo('add')">新增</a-button>
				<a-button type="primary" @click="importDatingRegistrationInfo(null)"
					>导出</a-button
				>
				<a-button type="primary" danger @click="batchDelDatingInfo"
					>删除</a-button
				>
			</a-space>
		</div>
		<div class="content">
			<a-table
				:dataSource="dataSource"
				:columns="columns"
				:loading="loading"
				:row-key="(record) => record.id"
				:pagination="pagination"
				@change="handleTableChange"
				:scroll="{ x: 'max-content', y: 370 }"
				:row-selection="rowSelection"
			>
				<template #bodyCell="{ column, record }">
					<template v-if="column.key === 'operation'">
						<a-space>
							<a-button
								type="primary"
								size="small"
								@click="editDatingInfo('update', record.id)"
								>编辑</a-button
							>
							<a-button
								type="primary"
								size="small"
								@click="importDatingRegistrationInfo(record.id)"
								>导出</a-button
							>
							<a-popconfirm
								title="确认删除?"
								ok-text="确认"
								cancel-text="取消"
								@confirm="delDatingInfo(record.id)"
								@cancel="cancel"
							>
								<a-button type="primary" size="small" danger>删除</a-button>
							</a-popconfirm>
						</a-space>
						<span></span>
					</template>
					<template v-else-if="column.key === 'startTime'">
						{{
							record.startTime ?
								dayjs(record.startTime).format('YYYY-MM-DD HH:mm:ss')
							:	''
						}}
					</template>
					<template v-else-if="column.key === 'endTime'">
						{{
							record.endTime ?
								dayjs(record.endTime).format('YYYY-MM-DD HH:mm:ss')
							:	''
						}}
					</template>
					<template v-else-if="column.key === 'payMoney'">
						{{
							record.payMoney === null ?
								''
							:	record.payMoney?.toFixed(2) || '0.00'
						}}
					</template>
					<template v-else-if="column.key === 'districtName'">
						{{ record?.cityName || null }} {{ record?.districtName || null }}
					</template>
					<template v-else-if="column.key === 'topFlag'">
						<a-tag
							:key="record?.topFlag"
							:color="record?.topFlag ? '#87d068' : 'red'"
						>
							{{ record?.topFlag ? '是' : '否' }}
						</a-tag>
					</template>
				</template>
			</a-table>
			<DatingInfoDetail
				ref="editInfo"
				:open="visible"
				:modelInfo="modelInfo"
				@handleOk="handleOk"
				@handleCancel="handleCancel"
			></DatingInfoDetail>
		</div>
	</div>
</template>
<script setup lang="ts">
import { columns, DataItem, ModelInfo, pageInfo, pagination, SearchInfo } from './datingInfoListTs';
import { deleteDatingInfo, getDatingInfoPage } from '@/api/datingInfo/datingInfo/datingInfoTs';
import { exportDatingRegistration } from '@/api/datingInfo/datingRegistrationInfo/datingRegistrationInfoTs';
import { message } from 'ant-design-vue';
import { getDictList } from '@/api/commonInfo/dictInfo/dictInfoTs';
import { dictInfo } from '@/views/commonInfo/dictInfo/dictInfoListTs';
import dayjs from 'dayjs';

const labelCol = ref({ span: 5 });
const wrapperCol = ref({ span: 19 });

let rowIds = [] as any;

const rowSelection = ref({
	checkStrictly: false,
	onChange: (
		selectedRowKeys: (string | number)[],
		selectedRows: DataItem[],
	) => {
		rowIds = selectedRowKeys;
	},
	onSelect: (record: DataItem, selected: boolean, selectedRows: DataItem[]) => {
		console.log(record, selected, selectedRows);
	},
	onSelectAll: (
		selected: boolean,
		selectedRows: DataItem[],
		changeRows: DataItem[],
	) => {
		console.log(selected, selectedRows, changeRows);
	},
});

const labelMap = ref<any>({
	datingType: { name: 'datingType', label: '约会类型' },
	startTime: { name: 'startTime', label: '约会开始时间' },
	startTimeFrom: { name: 'startTime', label: '约会时间从' },
	startTimeTo: { name: 'startTime', label: '约会时间到' },
	content: { name: 'content', label: '约会内容' },
	imageIds: { name: 'imageIds', label: '约会图片ID（逗号分隔）' },
	location: { name: 'location', label: '约会地点' },
	payMoney: { name: 'payMoney', label: '支付金额' },
});

let searchInfo = ref<SearchInfo>({ noTopFlagSort: true });

let datingTypeList = ref<dictInfo[]>([]);

const getDictInfoList = (): void => {
	getDictList('dateType').then((res) => {
		if (res.code == '200') {
			const filteredData = res.data.filter(
				(item: { belongTo: string }) => item.belongTo == 'dateType',
			);
			// Add "All" option at the beginning
			datingTypeList.value = [
				{ typeName: '全部', typeCode: '' },
				...filteredData,
			];
		} else {
			message.error((res && res.message) || '查询列表失败！');
		}
	});
};

const cancelQuery = (): void => {
	searchInfo.value = {};
};

const query = (): void => {
	getDatingInfoListPage(searchInfo.value, pagination.value);
};

const handleTableChange = (pagination): void => {
	getDatingInfoListPage(searchInfo.value, pagination);
};

const delDatingInfo = (ids: string): void => {
	deleteDatingInfo(ids).then((res) => {
		if (res.code == '200') {
			message.success((res && '删除' + res.message) || '删除成功！', 3);
			getDatingInfoListPage(searchInfo.value, pagination.value);
		} else {
			message.error((res && res.message) || '删除失败！', 3);
		}
	});
};

const batchDelDatingInfo = (): void => {
	let ids = '';
	if (rowIds && rowIds.length > 0) {
		rowIds.forEach((item: string) => {
			ids += item + ',';
		});
		ids = ids.substring(0, ids.length - 1);
	} else {
		message.warning('请先选择数据！', 3);
		return;
	}
	delDatingInfo(ids);
};

let loading = ref<boolean>(false);

let dataSource = ref();

const cancel = (e: MouseEvent): void => {
	console.log(e);
};

const importDatingRegistrationInfo = (datingId?: number | null) => {
	exportDatingRegistration({ datingId }, { responseType: 'blob' }) // 设置 responseType 为 'blob'
		.then((response) => {
			const blob = new Blob([response.data], {
				type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
			});
			const url = window.URL.createObjectURL(blob);
			const link = document.createElement('a');
			link.href = url;
			link.setAttribute('download', '用户参加约会名单.xlsx'); // 设置文件名
			document.body.appendChild(link);
			link.click();
			document.body.removeChild(link);
			window.URL.revokeObjectURL(url); // 释放内存
		})
		.catch((error) => {
			console.error('Error exporting Excel:', error);
		});
};

const getDatingInfoListPage = (param: SearchInfo, cur: pageInfo): void => {
	loading.value = true;
	getDatingInfoPage(param, cur.current, cur.pageSize)
		.then((res) => {
			if (res.code == '200') {
				dataSource.value = res.data.records;
				pagination.value.current = res.data.current;
				pagination.value.pageSize = res.data.size;
				pagination.value.total = res.data.total;
			} else {
				message.error((res && res.message) || '查询列表失败！');
			}
		})
		.finally(() => {
			loading.value = false;
		});
};

const init = (): void => {
	getDictInfoList();
	//获取约会表页面数据
	getDatingInfoListPage(searchInfo.value, pagination.value);
};

init();

let visible = ref<boolean>(false);

let modelInfo = ref<ModelInfo>({});

//新增和修改弹窗
const editDatingInfo = (type: string, id?: number): void => {
	if (type == 'add') {
		modelInfo.value.title = '新增明细';
		modelInfo.value.id = undefined;
	} else if (type == 'update') {
		modelInfo.value.title = '修改明细';
		modelInfo.value.id = id;
	}
	modelInfo.value.confirmLoading = true;
	visible.value = true;
};

const handleOk = (v: boolean): void => {
	visible.value = v;
	getDatingInfoListPage(searchInfo.value, pagination.value);
};

const handleCancel = (v: boolean): void => {
	visible.value = v;
};
</script>
<style lang="scss" scoped></style>
